<?php
namespace app\interfaces\controller;

use app\interfaces\model\MemberCoupon as MemberCouponModel;
use think\Request;
use think\Exception;

class MemberCoupon
{

    /*
     * 用户端 - 我的优惠券列表
     * @param  string $user_id      会员ID
     * @param  string $status       使用状态
     * @param  string $end_time     已过期
     */
    public function collect_list()
    {

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['user_id'])) throw new Exception('not Empty');

        // 默认搜索条件
        $condition['member_id'] = ['eq', $data['user_id']];

        // if (!empty($data['status'])) $condition['status'] = ['eq', '1'];
        // if (!empty($data['time'])) $condition['end_time'] = ['elt', time()];
        // 已使用
        if (!empty($data['status']) && empty($data['time'])) {
            $condition['status'] = 1;
        } elseif (empty($data['status']) && !empty($data['time'])) {
            // 已过期
            $condition['end_time'] = ['elt', time()];
            $condition['status'] = 2;
        } else {
            // 未使用
            $condition['status'] = 2;
            $condition['end_time'] = ['egt', time()];
        }
        // 读取
        $model = new MemberCouponModel();

        // 统计 1.未使用 2.已使用 3.已过期
        $Stat['unused'] = $model->where(['member_id' => $data['user_id'], 'end_time' => ['egt', time()], 'status' => '2'])->count();
        $Stat['been_used'] = $model->where(['member_id' => $data['user_id'], 'status' => '1'])->count();
        $Stat['stale'] = $model->where(['member_id' => $data['user_id'], 'end_time' => ['elt', time()], 'status' => '2'])->count();

        $result = $model->where($condition)
            ->field('member_id,shop_id,create_time,status,coupon_id', true)
            ->order(['id' => 'desc'])
            ->paginate(6);


        return ['code' => 200, 'message' => '成功', 'data' => $result, 'stat' => $Stat];
    }

}
